<template>
  <div id="app">
    <!-- 初始化加载状态 -->
    <div v-if="!initialized" class="app-loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      应用初始化中...
    </div>

    <!-- 主应用内容 -->
    <div v-else class="app-container">
      <!-- 顶部导航栏 -->
      <header class="app-header">
        <div class="header-content">
          <router-link to="/" class="logo-link">
            <img src="@/assets/logo.svg" alt="应用Logo" class="logo">
            <h1>用户认证系统</h1>
          </router-link>

          <!-- 登录状态显示 -->
          <div class="user-section" v-if="auth.isAuthenticated && auth.user">
            <nav class="main-nav">
              <!-- 公共菜单 -->
              <router-link to="/dashboard" class="nav-link" :class="{ active: isActive('/dashboard') }">
                首页
              </router-link>

              <!-- 角色专属菜单 -->
              <router-link
                  v-if="auth.user.userType === 'STUDENT'"
                  to="/student/papers"
                  class="nav-link"
                  :class="{ active: isActive('/student/papers') }"
              >
                学生论文管理
              </router-link>

              <router-link
                  v-if="auth.user.userType === 'TEACHER'"
                  to="/teacher/dashboard"
                  class="nav-link"
                  :class="{ active: isActive('/teacher/dashboard') }"
              >
                教师面板
              </router-link>

              <router-link
                  v-if="auth.user.userType === 'TEACHER'"
                  to="/teacher/paper-audit"
                  class="nav-link"
                  :class="{ active: isActive('/teacher/paper-audit') }"
              >
                论文审核
              </router-link>

              <router-link
                  v-if="auth.user.userType === 'ADMIN'"
                  to="/admin/dashboard"
                  class="nav-link"
                  :class="{ active: isActive('/admin/dashboard') }"
              >
                管理员面板
              </router-link>

              <router-link
                  v-if="auth.user.userType === 'ADMIN'"
                  to="/admin/users"
                  class="nav-link"
                  :class="{ active: isActive('/admin/users') }"
              >
                用户管理
              </router-link>

              <!-- 公共菜单 -->
              <router-link to="/user/profile" class="nav-link" :class="{ active: isActive('/user/profile') }">
                个人中心
              </router-link>
            </nav>

            <el-dropdown trigger="click" placement="bottom-end">
              <span class="user-avatar d-flex align-center">
                <el-avatar :src="auth.user?.avatar || defaultAvatar" />
                <span class="ml-2">{{ auth.user?.name || auth.user?.username || '用户' }}</span>
                <span class="user-badge" :class="roleClass">
                  {{ roleName }}
                </span>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goToProfile">
                    <i class="el-icon-user mr-2" />个人中心
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="logout">
                    <i class="el-icon-switch-button mr-2" />退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 未登录状态显示 -->
          <div class="auth-actions" v-else>
            <el-button link @click="navigateTo('/login')">登录</el-button>
            <el-button type="primary" @click="navigateTo('/register')">注册</el-button>
          </div>
        </div>
      </header>

      <!-- 主体内容 -->
      <main class="app-main">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </main>

      <!-- 页脚 -->
      <footer class="app-footer">
        <div class="footer-content">
          <p>&copy; {{ new Date().getFullYear() }} 用户认证系统 - 所有权利保留</p>
        </div>
      </footer>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useAuthStore } from '@/stores/auth';
import { Loading } from '@element-plus/icons-vue';
import defaultAvatar from '@/assets/default-avatar.png';

const router = useRouter();
const route = useRoute();
const auth = useAuthStore();
const initialized = ref(false);

// 检查路由是否激活 - 优化判断逻辑
const isActive = (path) => {
  return route.path === path ||
      (path !== '/' && route.path.startsWith(path));
};

// 导航方法
const navigateTo = (path) => {
  router.push(path);
};

// 个人中心
const goToProfile = () => {
  router.push('/user/profile');
};

// 退出登录 - 优化后的版本
const logout = async () => {
  try {
    // 确认对话框
    await ElMessageBox.confirm('确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 显示全屏加载
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在退出...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    try {
      // 执行退出
      await auth.logout();

      // 成功反馈
      ElMessage.success('已安全退出');

      // 跳转到登录页，使用replace避免回退
      await router.replace('/login');
    } catch (error) {
      // 退出失败处理
      console.error('退出失败:', error);
      ElMessage.error(`退出失败: ${error.message || '未知错误'}`);

      // 即使API调用失败也强制清除本地状态并跳转
      auth.clearAuthData();
      await router.replace('/login');
    } finally {
      // 关闭加载指示器
      loadingInstance.close();
    }
  } catch (error) {
    // 用户取消操作，不做任何处理
    console.log('用户取消退出');
  }
};

// 计算当前角色名称
const roleName = computed(() => {
  if (!auth.isAuthenticated || !auth.user) return '';

  switch (auth.user.userType) {
    case 'ADMIN': return '管理员';
    case 'TEACHER': return '教师';
    case 'STUDENT': return '学生';
    default: return '用户';
  }
});

// 计算角色徽章样式
const roleClass = computed(() => {
  if (!auth.isAuthenticated || !auth.user) return '';

  switch (auth.user.userType) {
    case 'ADMIN': return 'admin-badge';
    case 'TEACHER': return 'teacher-badge';
    case 'STUDENT': return 'student-badge';
    default: return '';
  }
});

// 组件初始化
onMounted(async () => {
  try {
    // 初始化认证状态
    await auth.initialize();

    // 监听认证状态变化
    watch(() => auth.isAuthenticated, (newVal) => {
      if (!newVal && !['/login', '/register'].includes(route.path)) {
        router.replace('/login');
      }
    });

    // 初始检查认证状态
    if (!auth.isAuthenticated && !['/login', '/register', '/'].includes(route.path)) {
      await router.replace('/login');
    }
  } catch (error) {
    console.error('应用初始化失败:', error);
    ElMessage.error('应用初始化失败，请刷新页面');
  } finally {
    initialized.value = true;
  }
});
</script>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.app-header {
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 0;
  position: sticky;
  top: 0;
  z-index: 1000;
  height: 60px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.logo-link {
  display: flex;
  align-items: center;
  text-decoration: none;
  color: #409EFF;
  height: 100%;
}

.logo-link:hover {
  opacity: 0.9;
}

.logo {
  height: 40px;
  margin-right: 1rem;
}

.app-header h1 {
  font-size: 1.5rem;
  font-weight: 600;
  margin: 0;
}

.user-section,
.auth-actions {
  display: flex;
  align-items: center;
}

.main-nav {
  display: flex;
  gap: 1.5rem;
  margin-right: 2rem;
}

.nav-link {
  position: relative;
  text-decoration: none;
  color: #303133;
  font-weight: 500;
  padding: 0.5rem 0;
  transition: all 0.3s ease;
}

.nav-link:hover {
  color: #409EFF;
  transform: translateY(-2px);
}

.nav-link.active {
  color: #409EFF;
}

.nav-link.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #409EFF;
  border-radius: 2px;
}

.user-avatar {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
  padding: 0.5rem;
  color: #606266;
}

.user-avatar:hover {
  color: #409EFF;
}

.auth-actions {
  gap: 1rem;
}

.app-main {
  flex: 1;
  padding: 2rem 0;
  max-width: 1200px;
  width: 100%;
  margin: 0 auto;
}

.app-footer {
  background-color: #f5f7fa;
  color: #909399;
  padding: 2rem 0;
  border-top: 1px solid #ebeef5;
  height: 80px;
}

.footer-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 2rem;
  text-align: center;
  font-size: 0.9rem;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease, transform 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

/* 响应式设计 - 优化移动端体验 */
@media (max-width: 768px) {
  .app-header {
    height: auto;
  }

  .header-content {
    flex-direction: column;
    gap: 1rem;
    padding: 1rem;
  }

  .user-section {
    flex-direction: column;
    gap: 1rem;
    width: 100%;
  }

  .main-nav {
    width: 100%;
    justify-content: space-around;
    flex-wrap: wrap;
    margin-right: 0;
    gap: 1rem;
  }

  .nav-link {
    padding: 0.5rem;
  }

  .app-main {
    padding: 1rem;
  }
}

/* 角色徽章样式 */
.user-badge {
  margin-left: 8px;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.admin-badge {
  background-color: #f56c6c;
  color: white;
}

.teacher-badge {
  background-color: #e6a23c;
  color: white;
}

.student-badge {
  background-color: #67c23a;
  color: white;
}

/* 加载状态样式 */
.app-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  gap: 10px;
  font-size: 1.2rem;
  color: #409EFF;
}

.is-loading {
  animation: rotating 2s linear infinite;
  font-size: 24px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
